<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    // 添加session检查
    String username = (String)session.getAttribute("username");
    String role = (String)session.getAttribute("role");
    if(username == null || role == null) {
        response.sendRedirect("../../login.jsp");
        return;
    }
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增司机</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .form-container {
            background-color: #fff;
            padding: 30px;
            width: 80%;
            max-width: 800px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            border-radius: 5px;
            position: relative;
        }
        .form-title {
            font-size: 24px;
            text-align: center;
            margin-bottom: 30px;
            color: #183a8a;
        }
        .form-row {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 20px;
            align-items: center;
        }
        .form-row label {
            flex: 0 0 20%;
            text-align: right;
            padding-right: 15px;
            font-weight: bold;
        }
        .form-row input[type="text"],
        .form-row input[type="date"],
        .form-row select,
        .form-row textarea,
        .form-row input[type="file"] {
            flex: 0 0 75%;
            padding: 8px 12px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-row textarea {
            height: 100px;
            resize: vertical;
        }
        .form-row input:required + span::after {
            content: "*";
            color: red;
            margin-left: 5px;
        }
        .button-container {
            text-align: center;
            margin-top: 30px;
        }
        .submit-btn {
            padding: 10px 25px;
            font-size: 16px;
            background-color: #183a8a;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .submit-btn:hover {
            background-color: #2450a7;
        }
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #183a8a;
            text-decoration: none;
        }
        .back-link:hover {
            text-decoration: underline;
        }
        .error-message {
            color: red;
            font-size: 14px;
            margin-top: 5px;
            text-align: center;
        }
        .required-hint {
            text-align: right;
            margin-top: 10px;
            color: #666;
            font-size: 14px;
        }
        .required-hint::before {
            content: "*";
            color: red;
            margin-right: 5px;
        }
        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            z-index: 1000;
        }
        .loading-spinner {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        .form-row input:focus,
        .form-row select:focus,
        .form-row textarea:focus {
            outline: none;
            border-color: #183a8a;
            box-shadow: 0 0 5px rgba(24, 58, 138, 0.3);
        }
        .error {
            border-color: #dc3545 !important;
        }
        .error-message {
            color: #dc3545;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }
        .password-container {
            position: relative;
            flex: 0 0 75%;
        }
        .password-toggle {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #666;
        }
        .password-toggle:hover {
            color: #183a8a;
        }
    </style>
</head>
<body>
<div class="form-container">
    <a href="${pageContext.request.contextPath}/DriversServlet?action=all" class="back-link">← 返回司机列表</a>
    <div class="form-title">新增司机信息</div>

    <%-- 显示错误信息 --%>
    <% String error = (String) request.getAttribute("error"); %>
    <% if (error != null) { %>
    <div class="error-message"><%= error %></div>
    <% } %>

    <form id="driverForm" action="DriversServlet" method="post" enctype="multipart/form-data" onsubmit="return validateForm()">
        <input type="hidden" name="action" value="driver">

        <div class="form-row">
            <label for="driverId">司机ID:</label>
            <input type="text" id="driverId" name="driverId" required
                   placeholder="请输入数字ID（如：1001）"
                   pattern="\d+" title="ID必须为数字">
            <span class="error-message" id="driverId-error"></span>
        </div>

        <div class="form-row">
            <label for="password">登录密码:</label>
            <div class="password-container">
                <input type="password" id="password" name="password" required
                       placeholder="请输入登录密码（6-20位字符）"
                       pattern=".{6,20}" title="密码长度需为6-20位">
                <span class="password-toggle" onclick="togglePassword()">👁️</span>
            </div>
            <span class="error-message" id="password-error"></span>
        </div>

        <div class="form-row">
            <label for="confirmPassword">确认密码:</label>
            <div class="password-container">
                <input type="password" id="confirmPassword" name="confirmPassword" required
                       placeholder="请再次输入密码"
                       pattern=".{6,20}" title="密码长度需为6-20位">
                <span class="password-toggle" onclick="toggleConfirmPassword()">👁️</span>
            </div>
            <span class="error-message" id="confirmPassword-error"></span>
        </div>

        <div class="form-row">
            <label for="driverName">姓名:</label>
            <input type="text" id="driverName" name="driverName" required
                   placeholder="请输入司机姓名（2-10个汉字）"
                   pattern="[\u4e00-\u9fa5]{2,10}" title="姓名需为2-10个汉字">
            <span class="error-message" id="driverName-error"></span>
        </div>

        <div class="form-row">
            <label for="phoneNumber">手机号码:</label>
            <input type="text" id="phoneNumber" name="phoneNumber" required
                   placeholder="请输入11位手机号"
                   pattern="1[3-9]\d{9}" title="请输入有效的手机号码">
            <span class="error-message" id="phoneNumber-error"></span>
        </div>

        <div class="form-row">
            <label for="email">电子邮箱:</label>
            <input type="email" id="email" name="email"
                   placeholder="可选填（示例：user@example.com）"
                   pattern="[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+">
            <span class="error-message" id="email-error"></span>
        </div>

        <div class="form-row">
            <label for="gender">性别:</label>
            <select id="gender" name="gender" required>
                <option value="">请选择性别</option>
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
            <span class="error-message" id="gender-error"></span>
        </div>

        <div class="form-row">
            <label for="driverLicenseNumber">驾驶证号:</label>
            <input type="text" id="driverLicenseNumber" name="driverLicenseNumber" required
                   placeholder="请输入驾驶证档案编号（如：123456789012）"
                   pattern="\d{12}" title="12位数字">
            <span class="error-message" id="driverLicenseNumber-error"></span>
        </div>

        <div class="form-row">
            <label for="driverLicenseExpirationDate">驾驶证有效期:</label>
            <input type="date" id="driverLicenseExpirationDate"
                   name="driverLicenseExpirationDate" required
                   min="<%= java.time.LocalDate.now().plusYears(1) %>"
                   title="有效期必须大于当前日期至少一年">
            <span class="error-message" id="driverLicenseExpirationDate-error"></span>
        </div>

        <div class="form-row">
            <label for="driverLicenseImage">驾驶证图片:</label>
            <input type="file" id="driverLicenseImage" name="driverLicenseImage"
                   accept="image/jpeg, image/png"
                   title="仅支持JPG/PNG格式，大小不超过5MB">
            <span class="error-message" id="driverLicenseImage-error"></span>
        </div>

        <div class="form-row">
            <label for="remarks">备注:</label>
            <textarea id="remarks" name="remarks"
                      placeholder="可选填（最多255字符）"
                      maxlength="255"></textarea>
        </div>

        <div class="required-hint">标记为星号(*)的字段为必填项</div>

        <div class="button-container">
            <button type="submit" class="submit-btn" id="submitBtn">提交信息</button>
        </div>
    </form>
</div>

<div class="loading" id="loading">
    <div class="loading-spinner">
        <img src="${pageContext.request.contextPath}/images/loading.gif" alt="加载中...">
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('driverForm');
    const loading = document.getElementById('loading');
    const submitBtn = document.getElementById('submitBtn');

    // 设置日期输入的最小值
    const dateInput = document.getElementById('driverLicenseExpirationDate');
    const today = new Date();
    const minDate = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
    dateInput.min = minDate.toISOString().split('T')[0];

    // 实时验证函数
    function validateField(field, pattern, errorMessage) {
        const errorElement = document.getElementById(field.id + '-error');
        if (!pattern.test(field.value)) {
            field.classList.add('error');
            errorElement.textContent = errorMessage;
            errorElement.style.display = 'block';
            return false;
        } else {
            field.classList.remove('error');
            errorElement.style.display = 'none';
            return true;
        }
    }

    // 添加实时验证
    document.getElementById('phoneNumber').addEventListener('input', function() {
        validateField(this, /^1[3-9]\d{9}$/, '请输入有效的11位手机号码');
    });

    document.getElementById('email').addEventListener('input', function() {
        if (this.value) {
            validateField(this, /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, '请输入有效的邮箱地址');
        }
    });

    // 表单提交验证
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        let isValid = true;
        
        // 验证所有必填字段
        const requiredFields = ['driverId', 'driverName', 'phoneNumber', 'gender', 
                              'driverLicenseNumber', 'driverLicenseExpirationDate'];
        
        requiredFields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (!field.value.trim()) {
                field.classList.add('error');
                document.getElementById(fieldId + '-error').textContent = '此字段为必填项';
                document.getElementById(fieldId + '-error').style.display = 'block';
                isValid = false;
            }
        });

        // 验证手机号
        if (!validateField(document.getElementById('phoneNumber'), 
            /^1[3-9]\d{9}$/, '请输入有效的11位手机号码')) {
            isValid = false;
        }

        // 验证邮箱（如果填写）
        const email = document.getElementById('email');
        if (email.value && !validateField(email, 
            /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, '请输入有效的邮箱地址')) {
            isValid = false;
        }

        // 验证图片
        const fileInput = document.getElementById('driverLicenseImage');
        if (fileInput.files.length > 0) {
            const file = fileInput.files[0];
            if (file.size > 5 * 1024 * 1024) {
                fileInput.classList.add('error');
                document.getElementById('driverLicenseImage-error').textContent = '图片大小不能超过5MB';
                document.getElementById('driverLicenseImage-error').style.display = 'block';
                isValid = false;
            }
        }

        // 验证密码
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        
        if (password.length < 6 || password.length > 20) {
            alert('密码长度必须在6-20位之间');
            isValid = false;
        }
        
        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            isValid = false;
        }

        if (isValid) {
            loading.style.display = 'block';
            submitBtn.disabled = true;
            form.submit();
        }
    });

    // 检查URL参数
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('success') === 'true') {
        alert("添加成功！");
        history.replaceState({}, document.title, window.location.pathname);
    } else if (urlParams.get('success') === 'error') {
        alert("添加失败！请检查数据或联系管理员");
        history.replaceState({}, document.title, window.location.pathname);
    }

    // 密码显示切换函数
    window.togglePassword = function() {
        const passwordInput = document.getElementById('password');
        passwordInput.type = passwordInput.type === 'password' ? 'text' : 'password';
    }

    window.toggleConfirmPassword = function() {
        const confirmInput = document.getElementById('confirmPassword');
        confirmInput.type = confirmInput.type === 'password' ? 'text' : 'password';
    }
});
</script>
</body>
</html>